package com.testing.thread;

/**
 * @author lzp
 */
public class TestSync {

    // 第一种锁的方式直接用object
    static class TestSync1 implements Runnable{
        private int count = 10;
        // 这样创建
        private Object object = new Object();

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (object){
                    count --;
                    System.out.println(Thread.currentThread().getName() + " count == " + count);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class TestSync2 implements Runnable{
        private int count = 10;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                m();
            }
        }

        public void m(){
            synchronized (this){ // 锁本类
                System.out.println(this.getClass());
                count --;
                System.out.println(Thread.currentThread().getName() + " count == " + count);
            }

        }
    }


    static class TestSync3 implements Runnable{
        private int count = 10;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                m();
            }
        }

        public synchronized void m(){ // 锁方法
            count --;
            System.out.println(Thread.currentThread().getName() + " count == " + count);
        }
    }

    static class TestSync4 implements Runnable{
        private int count = 10;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                m();
            }
        }

        public void m(){ // 锁方法
            synchronized (TestSync4.class){ // 直接锁类的模板
                count --;
                System.out.println(Thread.currentThread().getName() + " count == " + count);
            }

        }
    }

    public static void main(String[] args) {
        // new Thread(new  TestSync1()).start();
        new Thread(new  TestSync2()).start();
        // new Thread(new TestSync4()).start();
    }
}
